import axios, { AxiosInstance, AxiosRequestConfig, AxiosPromise, AxiosResponse, AxiosProxyConfig } from 'axios' //引入axios和定义在node_modules/axios/index.ts 文件里的类型声明
import config from '@/config'
const { api: { devApiBaseUrl,proApiBaseUrl } } = config
const apiBaseUrl = process.env.NODE_ENV === 'production' ? proApiBaseUrl : devApiBaseUrl

export interface ResponseData {
  code: number
  data?: any
  msg: string
}
class HttpRequest {
  // 定义一个接口请求类 用于创建一个axios请求实例
  constructor(public baseUrl: string = apiBaseUrl){
    this.baseUrl = baseUrl
  }
  public request(options: AxiosRequestConfig): AxiosPromise {
    const instence: AxiosInstance = axios.create()//创建axios实例 包含多个属性
    options = this.mergeConfig(options)
    this.intercepters(instence, options.url)
    return instence(options)
  }

  private intercepters(instance: AxiosInstance, url?: string){
    //在此添加请求响应拦截
    instance.interceptors.request.use((config: AxiosRequestConfig) => {
      // 接口请求所有配置 类型为AxiosRequestConfig
      // 如果修改接口请求配置 修改axios.default 字段
      return config
    }, (error) => {
      return Promise.reject(error)
    })
    instance.interceptors.response.use((res: AxiosResponse) => {
      const { data } = res//res的类型是AxiosResponse<any> 包含6个字段 其中data是服务端返回数据
      const { code, msg } = data
      if(code !== 0){
        console.error(msg)
      }
      return res
    }, (error) => {
      return Promise.reject(error)
    })
  }
  private mergeConfig(options: AxiosRequestConfig): AxiosRequestConfig {
    return Object.assign({ baseUrl : this.baseUrl}, options)
  }
}

export default HttpRequest
